package com.panghl.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.panghl.config.FileTypeUtil;
import com.panghl.config.MinioConfigurationProperties;
import com.panghl.mapper.SysAttachMapper;
import com.panghl.model.entity.SysAttach;
import com.panghl.model.vo.SysFileVO;
import com.panghl.service.IMinioService;
import com.panghl.service.ISysAttachService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author panghl
 * @Date 2021/9/22 14:43
 **/
@Service
public class SysAttachServiceImpl extends ServiceImpl<SysAttachMapper, SysAttach> implements ISysAttachService {

    @Autowired
    private IMinioService minioService;

    @Autowired
    private MinioConfigurationProperties properties;

    @Override
    public SysFileVO upload(MultipartFile file) {
        String upload = minioService.upload(file);
        SysAttach fileEntity = new SysAttach();
        // 如果upload返回的是空，则说明文件保存失败
        if (StringUtils.isBlank(upload)) {
            throw new RuntimeException("上传失败");
        }
        String filename = file.getOriginalFilename();

        fileEntity.setFileName(filename);
        fileEntity.setFileUrl(upload);
        fileEntity.setFileType(FileTypeUtil.getType(file).getFileType());
        fileEntity.setFileSize(file.getSize());
        fileEntity.setFileSuffix(filename.substring(filename.lastIndexOf(".")));
        baseMapper.insert(fileEntity);

        SysFileVO fileDetailVo = new SysFileVO();
        fileDetailVo.setFileName(fileEntity.getFileName());
        fileDetailVo.setFileUrl(fileEntity.getFileUrl());
        fileDetailVo.setFileSize(fileEntity.getFileSize());
        fileDetailVo.setFileType(fileEntity.getFileType());
        fileDetailVo.setFileId(fileEntity.getId());

        fileDetailVo.setFileUrl(properties.getPrefix() + "type="+ fileEntity.getFileType() + "&filePath=" + fileEntity.getFileUrl());
        return fileDetailVo;

    }

    @Override
    public Boolean download(String filePath, HttpServletResponse response) {
        return minioService.download(filePath, response);
    }

    @Override
    public Boolean preview(String filePath, String type, HttpServletResponse response) {
        return minioService.preview(filePath, type, response);
    }

    @Override
    public void preview2(String filePath, String type, HttpServletResponse response, HttpServletRequest request) {
        minioService.preview2(filePath, type, response, request);
    }

    @Override
    public Boolean deleteFile(String filePath) {
        return minioService.deleteFile(filePath);
    }

}
